<template>
  <div>

    <div >
      <div >
        <el-upload
          class="upload-pic"
          :action="domain"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :data="QiniuData"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :before-remove="beforeRemove"
          :before-upload="beforeAvatarUpload"
          :limit="limitCount"
          ref="upload"
          accept=".jpg, .jpeg, .png"
          :multiple="multiple"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">选择图片</el-button>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

      </div>
      <el-dialog :visible.sync="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>

    </div>

  </div>

</template>

<script>
  import md5 from 'js-md5';
  let Base64 = require('js-base64').Base64;
  export default {
    name: 'ImageUpload',
    data(){
      return{
        dialogImageUrl: '',
        dialogVisible: false,
        QiniuData: {
          key: "", //图片名字处理
          token: "" //七牛云token
        },
        domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
        qiniuaddr: "https://supimage.miniprogramhacker.cn", // 七牛云的图片外链地址
      }
    },
    /**
     * @property {Number} [limitCount = 1] limitCount 最多能传多少张图片
     * @property {Array} urlList 图片上传后，得到的地址列表数组
     * @property {Number} [fileSizeLimit = 20] fileSizeLimit 单图片大小限制，单位M，默认20M
     * @property {Boolean} [multiple = true] multiple 能否多选，默认是
     * @property {Array} fileList 回显图片数组 [{url:''}] 或者 [{url:'',name:''}] 的格式
     */
    props:{
      limitCount:{
        type: Number,
        default: 90
      },
      urlList:{
        type:Array,
        default:[],
        require:true
      },
      fileSizeLimit:{
        default:20
      },
      multiple:{
        default:true
      },
      fileList:{
        type: Array,
        default:()=>{}
      }
    },
    mounted() {
      if (this.isEmpty(this.$store.state.qiniuToken)){
        this.getQiniuToken()
      }


    },
    methods: {
      // === 移除  ===//
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleRemove(file, fileList) {
        // 截取回显时，url后面拼接参数导致匹配不到无法删除的问题
        let index = file.url.indexOf('?')
        var realUrl = file.url
        if (index > 0){
          realUrl = file.url.substring(0,index)
        }
        let _tmp = this.urlList;
        let localFile = !this.isEmptyStr(file.qiniuName)
        for (var i = 0, len = _tmp.length; i < len; i++) {
          if (localFile){
            if (_tmp[i].qiniuName == file.qiniuName) {
              _tmp.splice(i, 1);
              break;
            }
          } else {
            if (_tmp[i].url == realUrl) {
              _tmp.splice(i, 1);
              break;
            }
          }
        }
        if (localFile){
          this.getAxios('public/deleteImage',{
            fileName:file.qiniuName
          }).then(res => {
            console.log('删除七牛云图片成功')
          }).catch(error => {
            console.log('删除七牛云图片失败')
          })
        }
        this.urlList = _tmp;
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          '当前限制选择' + this.limitCount +' 张图片，如需更换，请删除上一张图片在重新选择！'
        );
      },
      // === 上传  ===//
      beforeAvatarUpload: function (file) {

        const isPNG = file.type === 'image/png'
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isLt20M = file.size / 1024 / 1024 < this.fileSizeLimit

        if (!isPNG && !isJPEG && !isJPG) {
          this.$message.error('上传图片只能是 jpg、png、jpeg 格式!')
          return false
        }
        if (!isLt20M) {
          this.$message.error('上传图片大小不能超过 '+this.fileSizeLimit+'MB!')
          return false
        }
        let randText = this.randomText(5)
        let timestamp = Date.parse(new Date())
        let baseN = Base64.encode(file.name)
        let mdName = md5(baseN+timestamp+randText)
        let key = 'uploadPic/'+mdName
        this.QiniuData.key = key
        this.urlList.push({
          qiniuName: key
        });
      },
      uploadSuccess(response, file, fileList) {

        var picUrl = `${this.qiniuaddr}/${response.key}`;
        file.qiniuName = response.key;

        var _tmp = this.urlList;

        for (let i = 0, len = _tmp.length; i < len; i++) {
          var map = _tmp[i]
          if (map.qiniuName == response.key){
            map.url = picUrl
            map.response = response
          }
        }
        this.urlList = _tmp

      },
      uploadError(err, file, fileList) {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true
        });
      },
      // === 预览  ===//
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 取消
      cancel(){
        this.$refs.upload.clearAllFile()
        this.urlList.splice(0,this.urlList.length);
      },
      //请求后台拿七牛云token
      getQiniuToken() {

        this.getAxios('public/qiniuToken').then(res => {

          this.QiniuData.token = res.data;

          this.$store.commit('updateQiniuToken', res.data)
        });
      },
      clearAllFile(){
        this.fileList.removeAll()
      }
    }
  }
</script>

<style scoped>

</style>
